<?php

	class dirObj {

		var $path;
		var $name;
		var $files = array();
		var $dirs = array();
		var $dirObjs = array();

		function __construct( $path ) {
			global $rootDir;
			$this->path = $path;
			$split = explode("/", $path);
			$this->name = $split[ count($split) - 1 ];
		}

		function prepare() {
			$myItem = array( "name" => $this->name, "path" => $this->path, "type" => "folder", "children" => array() );
			if ( count($this->dirObjs) > 0 ) {
				foreach( $this->dirObjs as $obj ) {
					$myItem["children"][] = $obj->prepare();
				}
			}
			if ( count($this->files) > 0 ) {
				$files = array();
				foreach( $this->files as $path => $name ) {
					$fileItem = array( "name" => $name, "path" => $path, "type" => "file" );
					//$myItem["children"][] = $fileItem;
					$files[$name] = $fileItem;
				}
				ksort($files);
				foreach( $files as $file ) $myItem["children"][] = $file;
			}
			return $myItem;
		}

	}

	function getDir( $dir ) {
		if ( !is_dir($dir) ) return false;
		if ( $dh = opendir($dir) ) {
			$dirObj = new dirObj( $dir );
			while ( ($file = readdir($dh)) !== false ) {
				if ( $file[0] == "." ) continue;
				if ( is_dir( $dir."/".$file ) ) $dirObj->dirs[] = $dir."/".$file;
				else $dirObj->files[$dir."/".$file] = $file;
			}
			closedir($dh);
		}
		if ( count($dirObj->dirs) > 0 ) {
			foreach( $dirObj->dirs as $dir ) {
				$dirObj->dirObjs[] = getDir( $dir );
			}
		}
		return $dirObj;
	}

	$rootDir = "media";
	$struct = getDir( $rootDir );
	$json = array( "identifier" => "path", "label" => "name", "items" => array() );
	$json["items"][] = $struct->prepare();
	
	//echo "\n".print_r($json,true)."\n";
	die( json_encode($json) );

?>
